package com.yzg.simple.netty.officialchat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author misterWei
 * @create 2020年01月01号:22点00分
 */
public class NettyOfficialTcpClient {

    private  final String host;
    private  final int port;
    protected EventLoopGroup clientGroup;
    public NettyOfficialTcpClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public void run() throws InterruptedException {
        clientGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                        .group(clientGroup)
                          .channel(NioSocketChannel.class)
                            .handler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel ch) throws Exception {
                                    ChannelPipeline pipeline = ch.pipeline();
                                    //编码器
                                    pipeline.addLast("encode",new StringEncoder());
                                    //解码器
                                    pipeline.addLast("decode",new StringDecoder());
                                    pipeline.addLast(new NettyOfficialTcpClientHandler());
                                }
                            });

            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()){
                channelFuture.channel().writeAndFlush(scanner.nextLine());
            }

            channelFuture.channel().closeFuture().sync();

        }finally {
            clientGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyOfficialTcpClient("127.0.0.1",6666).run();
    }

}
